package com.tuniondata.netty.bean;

import com.tuniondata.netty.common.protocol.Protocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

/**
 * @author yuxinchao
 */
public class MessageDecoder extends ByteToMessageDecoder {

    private static final Logger log = LoggerFactory.getLogger(MessageDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() <= 4) {
            return;
        }

        int len = in.readInt();

        if (len < 1 || in.readableBytes() < len) {
            return;
        }

        byte[] data = new byte[len];
        in.readBytes(data);

        log.info("decode len:{} data:{}", data.length, new String(data));

        RpcMessage rpcMessage = new RpcMessage(data);

        out.add(rpcMessage);
    }
}
